/**
 * 通用uni-app网络请求
 * 基于 Promise 对象实现更简单的 request 使用方式，支持请求和响应拦截
 */

/*
// 开放的接口
import http from './interface'

http.config.baseUrl = "http://localhost:8080/api/"

http.request(url:'user/list',method:'GET').then((res)=>{
	console.log(JSON.stringify(res))
})
http.get('user/list').then((res)=>{
	console.log(JSON.stringify(res))
})
http.get('user/list', {status: 1}).then((res)=>{
	console.log(JSON.stringify(res))
})
http.post('user', {id:1, status: 1}).then((res)=>{
	console.log(JSON.stringify(res))
})
http.put('user/1', {status: 2}).then((res)=>{
	console.log(JSON.stringify(res))
})
http.delete('user/1').then((res)=>{
	console.log(JSON.stringify(res))
}) 

*/

import signature from '@/common/request/signature'
import { getTime } from '@/common/utils/utils'
import store from '@/store'

const env = 'local'
		
let operateNumber = store.state.site.operateNumber

const config = {
	local: {
		domain: 'http://api.zfsaas.devp',
		// operate_number: '2108277716541085'
	},
	dev: {
		domain: 'http://api.linghuiyun.cn:6060',
		// operate_number: '2108277716541085'
	},
	test: {
		domain: 'http://api.linghuiyun.cn:7070',
		operate_number: '2108277716541085'
	},
	yanshi: {
		domain: 'https://api.linghuiyun.cn',
		operate_number: '2108277716541085'
	},
	prod: {
		domain: 'https://api.zfsaas.com',
		// operate_number: '2108277716541085'
	}
}

export default {
	config: {
		baseUrl: "",
		header: {
			'Content-Type':'application/json;charset=UTF-8',
			'Content-Type':'application/x-www-form-urlencoded'
		},
		data: {},
		method: "GET",
		dataType: "json",  /* 如设为json，会对返回的数据做一次 JSON.parse */
		sslVerify: false,
		responseType: "text",
		success() {},
		fail() {},
		complete() {}
	},
	interceptor: {
		request: null,
		response: null
	},
	request(options) {
		if (!options) {
			options = {}
		}
		
		this.config.baseUrl = config[env].domain

		options.baseUrl = options.baseUrl || this.config.baseUrl
		options.dataType = options.dataType || this.config.dataType
		options.url = options.baseUrl + options.url
		options.data = options.data || {}
		options.method = options.method || this.config.method
		//TODO 全局数据
		
		if(store.state.global.os.app){
			options.data.globalDeviceNumber = plus.device.getInfo('uuid') ? plus.device.getInfo('uuid') : ''
			options.data.globalVersion = plus.runtime.version + ' ' + plus.runtime.versionCode
		}

		if(store.state.global.os.android){
			options.data.globalSystem = 'android'
		}
		if(store.state.global.os.iphone){
			options.data.globalSystem = 'ios'
		}
		
		if(store.state.global.os.mp){
			options.data.globalSource = 'xcx'
		}
		if(store.state.global.os.app){
			options.data.globalSource = 'app'
		}
		if(store.state.global.os.h5){
			options.data.globalSource = 'h5'
		}
		
		options.data.globalSiteCode = store.state.site.globalSiteCode;
		options.data.globalSiteRank = store.state.site.globalSiteRank;
		
		options.data.globalOperateNumber = config[env].operate_number;
		
		//TODO 数据签名
		options.data.timestamp = getTime() + store.state.global.time_diff;
		
		Object.keys(options.data).forEach(function(key){
			// 过滤值为undefined的参数 否则影响小程序等的签名
			 if(options.data[key] == undefined){
				 delete options.data[key]
			 }
		})
		
		// 参数签名排序
		let dataObj = signature.objKeySort(options.data)
		// // 参数转字符串
		let dataStr = signature.urlEncode(dataObj, null, true)
		// console.log(dataStr)
		// // 参数字符串签名计算
		let signatureValue = signature.hex_sha1(dataStr + 'linghui_api_1619228244')
		let _token = {'x-token': store.state.user.token || ''};
		let _sign = {'signature': signatureValue};
		options.header = Object.assign({}, options.header, _token,_sign) 
	   
		return new Promise((resolve, reject) => {
			uni.getNetworkType({
			    success: function (res) {
					if(res.networkType == 'none'){
						uni.showToast({
							title: '当前网络不可用',
							icon: 'error',
							mask: true
						});
						reject()
					}
			    }
			});
			
			let _config = null
			
			options.complete = (response) => {
				let statusCode = response.statusCode
				let res = response.data
				response.config = _config
				if (process.env.NODE_ENV === 'development') {
					if (statusCode === 200) {
						// console.log("【" + _config.requestId + "】 结果：" + JSON.stringify(response.data))
					}
				}
				// if (this.interceptor.response) {
				// 	let newResponse = this.interceptor.response(response)
				// 	if (newResponse) {
				// 		response = newResponse
				// 	}
				// }
				
				// 统一的响应日志记录
				// _reslog(response)
				if (statusCode === 200) { //成功
					switch (res.code) {
						case -1:
						case 10004:
						case 10095:
						case 10096:
						case 10097:
						case 10099:
							console.log(res.message)
							console.log(options.url)
							break
						case 10001:
							console.log(res.message)
							store.commit('user/setMobile', null)
							store.commit('user/setToken', null)
							
							// #ifdef MP-WEIXIN
							uni.navigateTo({
								url: "/pages/login/weixin_oauth_login"
							})
							// #endif
							// #ifndef MP-WEIXIN
							uni.navigateTo({
								url: "/pages/login/form_login"
							})
							// #endif
							break
						case 10002:
						case 10003:
							console.log(res.message)
							store.commit('user/setMobile', null)
							store.commit('user/setToken', null)
							// reLaunch
							// #ifdef MP-WEIXIN
							uni.reLaunch({
								url: "/pages/login/weixin_oauth_login"
							})
							// #endif
							// #ifndef MP-WEIXIN
							uni.reLaunch({
								url: "/pages/login/form_login"
							})
							// #endif
							break
						case 40000:
							uni.showToast({
								title: res.message,
								icon: 'none',
								mask: true
							});
							break
					}
					
					resolve(response.data);
				} else {
					reject(response)
				}
			}

			_config = Object.assign({}, this.config, options)
			_config.requestId = new Date().getTime()

			if (this.interceptor.request) {
				this.interceptor.request(_config)
			}
			
			// 统一的请求日志记录
			// _reqlog(_config)

			// if (process.env.NODE_ENV === 'development') {
			// 	console.log("【" + _config.requestId + "】 地址：" + _config.url)
			// 	if (_config.data) {
			// 		console.log("【" + _config.requestId + "】 参数：" + JSON.stringify(_config.data))
			// 	}
			// }

			uni.request(_config);
		});
	},
	get(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'GET'  
		return this.request(options)
	},
	post(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'POST'
		return this.request(options)
	},
	put(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'PUT'
		return this.request(options)
	},
	delete(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'DELETE'
		return this.request(options)
	},
	uploadPublicFile(file) {
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: config[env].domain + '/common/upload_image/uploadOssPublicImage',
				filePath: file,
				name: 'image',
				formData: {},
				success: (uploadFileRes) => {
					resolve(JSON.parse(uploadFileRes.data));
				}
			});
		})
	}
}


/**
 * 请求接口日志记录
 */
function _reqlog(req) {
	if (process.env.NODE_ENV === 'development') {
		console.log("【" + req.requestId + "】 地址：" + req.url)
		if (req.data) {
			console.log("【" + req.requestId + "】 请求参数：" + JSON.stringify(req.data))
		}
	}
	//TODO 调接口异步写入日志数据库
}

/**
 * 响应接口日志记录
 */
function _reslog(res) {
	let _statusCode = res.statusCode;
	if (process.env.NODE_ENV === 'development') {
		console.log("【" + res.config.requestId + "】 地址：" + res.config.url)
		if (res.config.data) {
			console.log("【" + res.config.requestId + "】 请求参数：" + JSON.stringify(res.config.data))
		}
		console.log("【" + res.config.requestId + "】 响应结果：" + JSON.stringify(res))
	}
	//TODO 除了接口服务错误外，其他日志调接口异步写入日志数据库
	switch(_statusCode){
		case 200:
			break;
		case 401:
			break;
		case 404:
			break;
		default:
			break;
	}
}

